#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {
public:
    int pathSum(TreeNode* root, int targetSum)
    {
        int count = 0;
        _prevSumCountMap[0] = 1;

        GetPathSumByInOrder(root, targetSum, 0, count);

        return count;
    }

private:
    void GetPathSumByInOrder(TreeNode* root, int targetSum, long long prev, int& count)
    {
        if (root == nullptr) {
            return;
        }

        long long cur = prev + root->val;
        count += _prevSumCountMap[cur - targetSum];

        ++_prevSumCountMap[cur];

        GetPathSumByInOrder(root->left, targetSum, cur, count);
        GetPathSumByInOrder(root->right, targetSum, cur, count);

        --_prevSumCountMap[cur];
    }

    std::unordered_map<long long, int> _prevSumCountMap;
};